#include "stdafx.h"
#include "USplittedContainerWindow.h"
#include "UWindowThemer.h"
#include "UPopUpMenu.h"

using namespace std;

TSplittedContainerWindow::TSplittedContainerWindow(TRectangle Rect, TContainerWindow* parent, TWindowThemer *wt, std::string name)
	: TContainerWindow(Rect, parent, wt, name)
{
	Horizontal = true;
}

void TSplittedContainerWindow::ToggleDirection()
{
	Horizontal = !Horizontal;
	SetPos(TRectangle(Left, Top, Right, Bottom));

}

void TSplittedContainerWindow::AddToPopUpMenu(TPopUpMenu* Menu)
{
	TDockable::AddToPopUpMenu(Menu);
	Menu->AddEntry("Toggle Direction", boost::bind(&TSplittedContainerWindow::ToggleDirection, this));
}

void TSplittedContainerWindow:: Draw( )
{
	for (unsigned int i=0; i < Children.size(); ++i)
	{
		Children[i]->Draw();
	}

	TContainerWindow::Draw();
}

void TSplittedContainerWindow:: MouseMove(int X, int Y, int mstate)
{
	for (unsigned int i=0; i < Children.size(); ++i)
	{
		if (Children[i]->Contains(X, Y))
			Children[i]->MouseMove(X, Y, mstate);
	}

	TContainerWindow::MouseMove(X, Y, mstate);

}

void TSplittedContainerWindow:: MouseDown(int X, int Y, uint8 button)
{
	bool ChildContains = false;
	for (unsigned int i=0; i < Children.size(); ++i)
	{
		if (Children[i]->Contains(X, Y))
		{
			ActiveChildindex = i;
			Children[i]->MouseDown(X, Y, button);
			ChildContains = true;
		}
	}
	if (!ChildContains)
		TContainerWindow::MouseDown(X, Y, button);
}

void TSplittedContainerWindow:: MouseUp(int X, int Y, uint8 button)
{
	bool ChildContains = false;
	for (unsigned int i=0; i < Children.size(); ++i)
	{
		if (Children[i]->Contains(X, Y))
		{
			Children[i]->MouseUp(X, Y, button);
			ChildContains = true;
		}
	}
	if (!ChildContains)
		TContainerWindow::MouseUp(X, Y, button);
}

void TSplittedContainerWindow::SetPos(TRectangle Rect)
{
	TDockable::SetPos(Rect);
	size_t ChildCount = Children.size();

	if (Horizontal)
	{
		for (size_t i=0; i < ChildCount; ++i)
		{
			(Children[i]->SetPos(TRectangle(
				Left+((Right-Left)*(i    )/ChildCount),
				Top+ windowthemer->BorderTheme()->BorderTop(),
				Left+((Right-Left)*((i+1))/ChildCount),
				Bottom )));
		}
	}
	else
	{
		for (size_t i=0; i < ChildCount; ++i)
		{
			(Children[i]->SetPos(TRectangle(
				Left	,
				Top				+((Bottom-Top)*(i    )/ChildCount)+windowthemer->BorderTheme()->BorderTop(),
				Right	,
				Top				+((Bottom-Top)*(i+1)/ChildCount))));
		}
	}
}

void TSplittedContainerWindow::RemoveChild(TDockable* Child)
{
	Child->SetPos(TRectangle(Left, Top, Right, Bottom));
	TContainerWindow::RemoveChild(Child);
	SetPos(TRectangle(Left, Top, Right, Bottom));

	if (Children.size()==1)
	{
		Parent->AddChild(Children[0]);
		Parent->RemoveChild(this);
		Children[0]->SetPos(TRectangle(Left, Top, Right, Bottom));
	}

}
